﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.UI.Common.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
    public class PubListPresenter
    {
        private PubListView _View;
		/// <summary></summary>
		public PubListView View
		{
			get
			{
				return this._View;
			}
			set
			{
				this._View = value;
				if(this._View !=null)
				{
					this._View.PubSelected += new PubListView.OnPubSelected(SelectPub);
					this._View.Pubs = this.ReadPubList();
				}
			}
		}

		private readonly IEventAggregator _EventAggregator;
        private SubscriptionToken _SubscriptionToken;

        public PubListPresenter(IEventAggregator eventAggregator)
		{
			this._EventAggregator = eventAggregator;
		}

        public void SelectPub(PublicationDO pub)
        {
            if (pub != null)
            {
                this._EventAggregator.GetEvent<PublicationSelectedEvent>().Publish(pub);
            }
        }

        public void RegisterPubSelectionChangedEventHandler(PublicationDO pub)
        {
            PublicationSelectedEvent publicationSelectedEvent =
                    _EventAggregator.GetEvent<PublicationSelectedEvent>();
            if (this._SubscriptionToken != null)
            {
                publicationSelectedEvent.Unsubscribe(_SubscriptionToken);
            }
            this._SubscriptionToken = publicationSelectedEvent.Subscribe(
                PubSelectedHandler,
                ThreadOption.UIThread,
                false);
        }

        private void PubSelectedHandler(PublicationDO pub)
        {
            this._View.SelectPub(pub);
        }

        private List<PublicationDO> ReadPubList()
        {
            return EntityManager.GeneratPubsForTest();
        }
    }
}
